import java.util.ArrayList;

public class ThreadObserver implements Runnable{

    private int countOfThreads = 1;
    private ArrayList<String> links;
    private String outputDirectory;
    private ArrayList<Thread> threads = new ArrayList<Thread>();
    private int workingThreadsCount = 0;

    public ThreadObserver(int countOfThreads, String outputDirectory, ArrayList<String> links){
        if(countOfThreads > 0)
            this.countOfThreads = countOfThreads;
        this.outputDirectory = outputDirectory;
        this.links = links;
    }

    private boolean clearCompletedProcesses(){
        for(int i = 0; i < threads.size(); i++){
            if(!threads.get(i).isAlive()){
                threads.remove(i);
                this.workingThreadsCount--;
            }
        }
        return threads.size() == 0;
    }

    private String getMinLink(String link){
        if(link.length() > 50){
            return link.subSequence(0, 20) + "..." + link.subSequence(link.length() - 17, link.length());
        }
        return link;
    }

    private void observer(){
        int currentThread = 0;
        while(currentThread < links.size()){
            clearCompletedProcesses();
            if(workingThreadsCount < countOfThreads){
                System.out.println("Starting new download " + getMinLink(links.get(currentThread)) + "\n");
                Thread t = new Thread(new WGet(links.get(currentThread++), this.outputDirectory));
                threads.add(t);
                t.start();
                workingThreadsCount++;
            }
        }
        for(int i = 0; i < threads.size(); i++){
            if(!threads.get(i).isAlive()){
                threads.remove(i);
                workingThreadsCount--;
            }
        }
        while(!clearCompletedProcesses());
        System.out.println("Finished downloading all the files" + "\n");
    }

    public void run() {
        observer();
    }

}
